import  {reqCartList,reqDeleteCartById,reqUpdateChecked} from '@/api'
const state = {
    cartList:[],
};
const mutations = {
    GETCARTLIST(state,cartList){
        state.cartList = cartList

    }
};
const actions = {
 async getCartList({commit}){
      let result = await reqCartList();
    if(result.code == 200){
        commit("GETCARTLIST",result.data)
    }
    },
    // 删除购物车产品
   async deleteCartListBySkuId({commit},skuid){
     let result =  await  reqDeleteCartById(skuid);
      if(result.code == 200){
        return 'ok';
      }else{
        return Promise.reject(new Error('faile'));
      }


    },
     //修改某一个商品勾选状态
     async changeChecked({ commit, state, dispatch }, { skuid, isChecked }) {
        let result = await reqUpdateChecked(skuid, isChecked);
        if (result.code == 200) {
             return 'ok';
        } else {
             return Promise.reject();
        }

   },
    //删除选中的商品
    deleteAllCart({ dispatch,getters }) {

        // context:小仓库
        // 获取购物车中全部的产品
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item=>{
         let  promise =  item.isChecked ==1? dispatch('deleteCartListBySkuId',item.skuId):'';
        //  每次调用一次deleteCartListBySkuId就会返回一次promise结果，所以把他们存在数组中
        PromiseAll.push(promise);
        })
        // 只要全部的p1|P2..都成功，返回结果即为成功
        // 如果一个失败，返回即为失败
        return Promise.all(PromiseAll)
       
   },
    // 修改全部产品的选中状态
    updateIsChecked({dispatch,state},isChecked){
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach(item=>{
       let promise =   dispatch('changeChecked',{ skuid:item.skuId, isChecked })
       PromiseAll.push(promise);
        });
       
       return Promise.all(PromiseAll)
    }

};
const getters ={
    cartList(state){
        return state.cartList[0] || {}

    },
    // 计算出来购物出数据
   

};
export default{
    state,
    mutations,
    actions,
    getters

}